package com.hae.shop.micoshopportalweb.controller.member;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.constant.Constants;
import com.hae.shop.common.util.BeanConvertUtil;
import com.hae.shop.common.util.OtherUtils;
import com.hae.shop.member.model.reqDto.QQAutoLoginReqDto;
import com.hae.shop.member.model.reqDto.QQBindLoginReqDto;
import com.hae.shop.member.model.respDto.UserLoginRespDto;
import com.hae.shop.micoshopportalweb.controller.member.feign.MemberFeign;
import com.hae.shop.micoshopportalweb.controller.member.vo.LoginReqVo;
import com.hae.shop.micoshopportalweb.utils.CookieUtils;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * QQ登录相关
 */
@Controller
@Slf4j
public class QQAuthoriController {

    @Autowired
    private MemberFeign memberFeign;

    @RequestMapping("qqloginx")
    public String qqloginx(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        request.setAttribute("avatarURL100", null);
        session.setAttribute(Constants.LOGIN_QQ_OPENID, "test");
        return Constants.MB_QQ_QQLOGIN;
    }

    /**
     * 调用QQ开放接口获取token
     * @param request
     * @return
     */
    @RequestMapping("/qqAuth")
    public String qqAuth(HttpServletRequest request) {
        try {
            return Constants.REDIRECT_INDEX + new Oauth().getAuthorizeURL(request); //Constants.REDIRECT_INDEX +
        } catch (Exception e) {
            return Constants.ERROR_FTL;
        }
    }


    /**
     * QQ登录回调
     * @return
     */
    @RequestMapping("qqLoginBack")
    public String qqLoginBack(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        try {
            //取得accessTokenObj
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            if (accessTokenObj == null) {
                return Constants.ERROR_FTL;
            }
            String accessToken = accessTokenObj.getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
                return Constants.ERROR_FTL;
            }
            // 获取用户openid
            OpenID openIDObj = new OpenID(accessToken);
            String openId = openIDObj.getUserOpenID();
            if (StringUtils.isEmpty(openId)) {
                return Constants.ERROR_FTL;
            }
            // 使用qq_openid调用会员服务进行自动登录
            QQAutoLoginReqDto loginReqDto = new QQAutoLoginReqDto();
            loginReqDto.setQqOpenId(openId);
            loginReqDto.setLoginType(Constants.MEMBER_LOGIN_TYPE_PC);
            loginReqDto.setDeviceInfor(OtherUtils.webBrowserInfo(request));
            Response<UserLoginRespDto> loginRespDtoResponse = memberFeign.autoLoginByQQ(loginReqDto);
            // 登录不成功则返回错误页面
            if (!loginRespDtoResponse.isSuccess()) {
                log.error("系统内部异常", loginRespDtoResponse.getErrorMsg());
                return Constants.ERROR_FTL;
            }
            // 登录结果为空，跳转到用户绑定界面
            if (StringUtils.isEmpty(loginRespDtoResponse.getResult().getUserid())) {
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openId);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                if (userInfoBean == null) {
                    return Constants.ERROR_FTL;
                }
                // 返回用户头像页面展示并将openId放入session以备登录
                request.setAttribute("avatarURL100", userInfoBean.getAvatar().getAvatarURL100());
                session.setAttribute(Constants.LOGIN_QQ_OPENID, openId);
                return Constants.MB_QQ_QQLOGIN;
            }
            // 登陆成功之后如何处理 保持会话信息 将token存入到cookie 里面 首页读取cookietoken 查询用户信息返回到页面展示
            request.setAttribute("member_id", loginRespDtoResponse.getResult().getUserid());
            CookieUtils.setCookie(request, response, Constants.LOGIN_TOKEN_COOKIENAME, loginRespDtoResponse.getResult().getToken());
            return Constants.INDEX_FTL;
        } catch (Exception e) {
            log.error("系统内部异常", e);
            // 发生异常则返回错误页面
            return Constants.ERROR_FTL;

        }
    }

    /**
     * qq绑定登录
     * @param loginReqVo 页面请求
     * @param model
     * @param request
     * @param response
     * @param httpSession
     * @return
     */
    @RequestMapping("/qqJointLogin")
    public String qqJointLogin(@ModelAttribute("loginVo") LoginReqVo loginReqVo, Model model, HttpServletRequest request,
                               HttpServletResponse response, HttpSession httpSession) {
        // 1.根据登录类型从session中获取用户openid（是否可能线程不安全）
        String openId;
        if (loginReqVo.getType().equals("QQ")) {
            openId = (String) httpSession.getAttribute(Constants.LOGIN_QQ_OPENID);
        } else {
            openId = (String) httpSession.getAttribute(Constants.LOGIN_WX_OPENID);
        }
        if (StringUtils.isEmpty(openId)) {
            return Constants.ERROR_FTL;
        }
        // 2.将vo转换dto调用qq会员登陆接口
        QQBindLoginReqDto loginReqDto = BeanConvertUtil.EToT(loginReqVo, QQBindLoginReqDto.class);
        loginReqDto.setOpenId(openId);
        loginReqDto.setLoginType(Constants.MEMBER_LOGIN_TYPE_PC);
        String info = OtherUtils.webBrowserInfo(request);
        loginReqDto.setDeviceInfor(info);
        Response<UserLoginRespDto> loginRespDtoResponse;
        try {
            loginRespDtoResponse = memberFeign.bindloginByQQ(loginReqDto);
        } catch (Exception e) {
            log.error("系统内部异常", e);
            // 发生异常则返回错误页面
            return Constants.ERROR_FTL;
        }
        // 3.登录不成功返回错误
        if (!loginRespDtoResponse.isSuccess()) {
            model.addAttribute("error", loginRespDtoResponse.getErrorMsg());
            return Constants.MB_QQ_QQLOGIN;
        }
        // 4.登陆成功之后如何处理 保持会话信息 将token存入到cookie 里面 首页读取cookietoken 查询用户信息返回到页面展示
        model.addAttribute("member_id", loginRespDtoResponse.getResult().getUserid());
        CookieUtils.setCookie(request, response, Constants.LOGIN_TOKEN_COOKIENAME, loginRespDtoResponse.getResult().getToken());
        return Constants.INDEX_FTL; //REDIRECT_INDEX 省去跳转
    }

}
